package com.resource.utils;

import com.alibaba.fastjson.JSONException;
import com.resource.constant.AbstractErrorCode;
import com.resource.constant.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 自定义异常
 *
 * @Author Tao.yu
 * @Date 2019/10/28 15:57
 **/
@Slf4j
public class ServiceException extends RuntimeException implements Serializable {
	private static final long serialVersionUID = 1L;
	/**
	 * 异常对应的返回码
	 */
	private Integer errorCode;
	/**
	 * 异常对应的返回信息
	 */
	private String errorMessage;

	public Integer getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(Integer errorCode) {
		this.errorCode = errorCode;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public ServiceException(String errorMessage) {
		super(errorMessage);
		this.errorCode = AbstractErrorCode.SC_EXPECTATION_FAILED;
		this.errorMessage = errorMessage;
	}

	public ServiceException(ErrorCode anEnum) {
		super(anEnum.getMessage());
		this.errorCode = anEnum.getCode();
		this.errorMessage = anEnum.getMessage();
	}

	public ServiceException(String errorMessage, Integer errorCode) {
		super(errorMessage);
		this.errorMessage = errorMessage;
		this.errorCode = errorCode;
	}

	public ServiceException(String errorMessage, Throwable cause) {
		super(errorMessage, cause);
	}

	public ServiceException(Throwable cause) {
		super(cause);
	}

	/**
	 * 异常转换
	 */
	public static ServiceException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			log.error("异常信息", e);
			//FastJson 对象转换异常
			if(e instanceof JSONException){
				return new ServiceException(ErrorCode.FAST_JSON_CODE);
			}
			if(e instanceof NullPointerException){
				return new ServiceException(ErrorCode.NOLL_ERROR_CODE);
			}
			return new ServiceException(ErrorCode.SYS);
		}
		return new ServiceException("PRC服务异常,请联系开发人员！", 10011);
	}

}
